import { useState, useEffect } from 'react';
import { Table, Input, Button, Form, Row, Col, Card, Space, App, Modal, Select } from 'antd';
import { getDictList, deleteDict, addDict, updateDict, getDictById, getDictByCode } from '@/api/dict';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import DictForm from './SuperDictForm';

const SuperDict = () => {
  const [form] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { modal,message } = App.useApp();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [system, setSystem] = useState('admin'); // 添加系统状态，默认为admin
  
  // 详情模态框相关状态
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailData, setDetailData] = useState([]);
  const [detailPagination, setDetailPagination] = useState({
    current: 1,
    size: 10,
    total: 0
  });
  const [currentDictCode, setCurrentDictCode] = useState('');
  
  const getColumns = () => {
    const baseColumns = [
      {
        title: '字典编码',
        dataIndex: 'dictCode',
        key: 'dictCode'
      },
      {
        title: '数据库表名',
        dataIndex: 'tableName',
        key: 'tableName'
      },
      {
        title: '含义列',
        dataIndex: 'label',
        key: 'label'
      },
      {
        title: '值列',
        dataIndex: 'value',
        key: 'value'
      }
    ];

    if(hasElementAuth(['edit','delete','dictDetail'])){
      baseColumns.push(
        {
          title: '操作',
          key: 'action',
          width: 300,
          render: (_, record) => (
            <Space>
              <AuthControl permission="dictDetail">
                <Button icon={<SearchOutlined />} onClick={() => showDetailModal(record.dictCode)}>详情</Button>
              </AuthControl>
              <AuthControl permission="edit">
                <Button icon={<EditOutlined />} onClick={() => openEditModal(record, system)}>编辑</Button>
              </AuthControl>
              <AuthControl permission="delete">
                <Button icon={<DeleteOutlined />} onClick={()=>deleteById(record.id, system)} danger>删除</Button>
              </AuthControl>
            </Space >
          )
        }
      );
    }
    return baseColumns;
  };

  const [searchForm, setSearchForm] = useState({
    dictCode: "",
    tableName: "",
    size: 10,
    current: 1
  });
  
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);

  /**
   * 查询字典列表
   */
  const searchDicts = (formData, systemParam = system) => {
    setLoading(true);
    const params = formData || searchForm;
    getDictList(systemParam, params)
      .then(res => {
        if (res.data && res.data.others) {
          setTableData(res.data.others);
          setTotal(res.data.total || 0);
        } else {
          setTableData([]);
          setTotal(0);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };
  
  /**
   * 删除字典
   */
  const deleteById = (id, systemParam = system) => {
    modal.confirm({
      title: '确定要删除吗？',
      content: '此操作将永久删除该数据，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        deleteDict(systemParam, id).then(() => {
          message.success("字典已删除");
          searchDicts();
        })
        .finally(() => {
          setLoading(false);
        });
      }
    });
  };
  
  /**
   * 打开新增模态框
   */
  const openAddModal = () => {
    setIsEditing(false);
    addEditForm.resetFields();
    setIsModalOpen(true);
  };
  
  /**
   * 打开编辑模态框
   */
  const openEditModal = (record, systemParam = system) => {
    setModalLoading(true);
    setIsEditing(true);
    setIsModalOpen(true);
    
    // 调用接口获取详细信息
    getDictById(systemParam, record.id).then(res => {
      if (res.data) {
        addEditForm.setFieldsValue(res.data);
      }
    })
    .finally(() => {
      setModalLoading(false);
    });
  };
  
  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalOpen(false);
    addEditForm.resetFields();
    setIsEditing(false);
  };
  
  /**
   * 保存字典数据
   */
  const saveDictData = () => {
    addEditForm.validateFields().then(values => {
      setModalLoading(true);
      if (isEditing) {
        // 修改
        const updateData = {
          id: values.id,
          tableName: values.tableName,
          label: values.label,
          value: values.value,
          conditions: values.conditions,
          remark: values.remark
        };
        updateDict(system, updateData).then(() => {
          message.success("字典信息已更新");
          closeModal();
          searchDicts();
        })
        .finally(() => {
          setModalLoading(false);
        });
      } else {
        // 新增
        const addData = {
          dictCode: values.dictCode,
          tableName: values.tableName,
          label: values.label,
          value: values.value,
          conditions: values.conditions,
          remark: values.remark
        };
        addDict(system, addData).then(() => {
          message.success("新字典已添加");
          closeModal();
          searchDicts();
        })
        .finally(() => {
          setModalLoading(false);
        });
      }
    })
  };

  /**
   * 显示详情模态框
   */
  const showDetailModal = (dictCode) => {
    setCurrentDictCode(dictCode);
    setDetailModalOpen(true);
    fetchDictDetail(dictCode, 1, 10);
  };

  /**
   * 获取字典详情数据
   */
  const fetchDictDetail = (dictCode, current, size) => {
    setDetailLoading(true);
    const params = {
      dictCode: dictCode,
      current: current,
      size: size
    };
    
    getDictByCode(system, params)
      .then(res => {
        if (res.data && res.data.others) {
          setDetailData(res.data.others);
          setDetailPagination({
            current: res.data.current || current,
            size: res.data.size || size,
            total: res.data.total || 0
          });
        } else {
          setDetailData([]);
          setDetailPagination({
            current: 1,
            size: 10,
            total: 0
          });
        }
      })
      .finally(() => {
        setDetailLoading(false);
      });
  };

  /**
   * 处理详情分页变化
   */
  const handleDetailTableChange = (pagination) => {
    fetchDictDetail(currentDictCode, pagination.current, pagination.pageSize);
  };

  /**
   * 关闭详情模态框
   */
  const closeDetailModal = () => {
    setDetailModalOpen(false);
    setDetailData([]);
    setDetailPagination({
      current: 1,
      size: 10,
      total: 0
    });
  };

  useEffect(() => {
    searchDicts();
  }, [system]); // 添加system作为依赖项

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };
    
    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }
    
    setSearchForm(formData);
    searchDicts(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      dictCode: values.dictCode || "",
      tableName: values.tableName || "",
      current: 1
    };
    setSearchForm(formData);
    searchDicts(formData);
  };

  const [systemOptions, setSystemOptions] = useState([{ label: 'admin', value: 'admin' }]);
  const allDictSystems = ()=>{
    getDictByCode('admin', { dictCode: 'dictSystem' }).then(res => {
      setSystemOptions(res.data.others)
    });
  }
  useEffect(()=>{
    allDictSystems()
  },[])

  // 详情模态框的列定义
  const detailColumns = [
    {
      title: '标签',
      dataIndex: 'label',
      key: 'label'
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value'
    }
  ];

  return (
    <Card>
      <AuthControl permission="search">
        <Form form={form} onFinish={handleSearch}>
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item label="系统">
                <Select 
                  value={system} 
                  onChange={setSystem}
                  options={systemOptions}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="dictCode" label="字典编码">
                <Input placeholder="请输入字典编码" allowClear/>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="tableName" label="表名">
                <Input placeholder="请输入字典名称" allowClear/>
              </Form.Item>
            </Col>
            <Col span={6} style={{ textAlign: 'right' }}>
              <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />} style={{ marginRight: 8 }}>
                    查询
                  </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </AuthControl>
      <AuthControl permission="add">
        <Button loading={loading} type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={openAddModal}>
          添加
        </Button>
      </AuthControl>
      <Table 
        columns={getColumns()}
        dataSource={tableData} 
        rowKey="id" 
        loading={loading}
        scroll={{ y: '35vh' }}
        pagination={{
          current: searchForm.current,
          pageSize: searchForm.size,
          total: total,
          showTotal: (total) => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5','10', '20', '50', '100']
        }}
        onChange={handleTableChange}
      />
      
      {/* 新增/编辑模态框 */}
      <Modal
        title={isEditing ? "编辑字典" : "新增字典"}
        open={isModalOpen}
        onCancel={closeModal}
        confirmLoading={modalLoading}
        onOk={saveDictData}
        okText="保存"
        cancelText="取消"
      >
        <DictForm form={addEditForm} isEditing={isEditing} />
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title={`字典详情 - ${currentDictCode}`}
        open={detailModalOpen}
        onCancel={closeDetailModal}
        footer={null}
        width={800}
      >
        <Table
          columns={detailColumns}
          dataSource={detailData}
          loading={detailLoading}
          rowKey={(record, index) => index}
          pagination={{
            current: detailPagination.current,
            pageSize: detailPagination.size,
            total: detailPagination.total,
            showTotal: (total) => `共 ${total} 条数据`,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50']
          }}
          onChange={handleDetailTableChange}
        />
      </Modal>
    </Card>
  );
};

export default SuperDict;